package com.devunion.salon.dataload;

import org.springframework.context.ApplicationContext;
import org.springframework.orm.jpa.JpaTemplate;
import org.springframework.transaction.annotation.Transactional;
import com.devunion.salon.core.model.security.User;
import com.devunion.salon.core.model.security.Privilege;
import com.devunion.salon.core.model.security.Role;
import com.devunion.salon.core.model.security.PersonRole;

import javax.persistence.EntityManager;
import java.util.List;

/**
 * @author spetrakovsky
 */
public class AdministratorLoader implements EntityLoader {

    /**
     * Create user with login 'admin' and password 'admin' granted all privileges wich exists in application (db lookup).
     */
    @Transactional
    public void loadEntityes(ApplicationContext context, EntityManager em) {
        User user = new User();
        user.setLoginName("admin");
        user.setPassword("admin");
        em.persist(user);

        List<Privilege> privileges = em.createQuery("select prv from Privilege prv").getResultList();

        Role role = new Role();
        role.setName("administrator");
        role.setPrivileges(privileges);

        em.persist(role);

        PersonRole personRole = new PersonRole();
        personRole.setRole(role);
        personRole.setUser(user);

        em.persist(personRole);


    }
}
